package com.ailot.cloud.upms.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ailot.cloud.upms.common.dto.TreeNode;
import com.google.common.collect.Lists;
import lombok.experimental.UtilityClass;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@UtilityClass
public class TreeUtil {

    /**
     * 树构建
     *
     * @param <T>      实体
     * @param list     源数据集合
     * @param parentId 父ID
     * @return List
     */
    public <T extends TreeNode> List<T> build(List<T> list, String parentId) {
        List<T> treeList = CollUtil.newArrayList();
        for (T obj : list) {
            if (ObjectUtil.equals(parentId, obj.getParentId())) {
                treeList.add(obj);
                innerBuild(list, obj, 0);
            }
        }
        // 排序
        treeList = treeList.stream().sorted(Comparator.comparingInt(TreeNode::getSort)).collect(Collectors.toList());
        return treeList;
    }

    /**
     * 递归处理
     *
     * @param treeNodes  数据集合
     * @param parentNode 当前节点
     * @param deep       已递归深度
     */
    private <T extends TreeNode> void innerBuild(List<T> treeNodes, T parentNode, int deep) {

        if (CollUtil.isEmpty(treeNodes)) {
            return;
        }

        for (T childNode : treeNodes) {
            if (parentNode.getId().equals(childNode.getParentId())) {
                if (parentNode.getChildren() == null) {
                    parentNode.setChildren(Lists.newArrayList());
                }
                parentNode.addChildren(childNode);
                innerBuild(treeNodes, childNode, deep + 1);
            }
        }
    }

}
